<?php
namespace Admin\Controller;
use Admin\Common\BaseController;
class ProductController extends BaseController {
    public function index(){
        $product = M('product');
    	$search = I('get.search');
    	
    	if(!empty($search)){
    		$where = "product like '%".$search."%'";
    	}else{
    		$where = "";
    	}

    	$count = $product -> where($where) -> count();
    	$page = new \Think\Page($count,10);
    	$show = $page -> show();
    	$limit = $page -> firstRow.','.$page -> listRows;
    	$data = $product -> limit($limit) -> where($where) -> select();
    	
    	$this -> pagestr = $show;
        $this -> assign('search',$search);
    	$this -> assign('data',$data);
        $this -> display();
    }

    public function add(){
    	$this -> assign('title','添加产品');
    	$this -> display();
    }

    public function insert(){
    	$product = M('product');

    	$product -> create();

    	$res = $product -> add();

    	if($res){
    		echo "<script>
				alert('添加成功');
				window.location.href='".U('Admin/Product/index')."';
				</script>";
    	}else{
    		echo "<script>
				alert('添加失败,请重新添加');
				window.location.href='".U('Admin/Product/add')."';
				</script>";
    	}

    }

    public function edit(){
    	$id = I('get.id');
    	$product = M('product');
    	$data = $product -> where('id = "'.$id.'"') -> find();

    	$this -> assign('data',$data);
    	$this -> display();
    }

    public function update(){
    	$product = M('product');
    	$id = (int)I('post.id');
    	$product -> create();

    	$res = $product -> save();
    	if($res){
    		echo "<script>
					alert('用户修改成功');
					window.location.href='".U('Admin/Product/index')."';
			</script>";
    	}else{
    		echo "<script>
					alert('用户修改失败');
					window.location.href='".U('Admin/Product/edit',array('id'=>$id))."';
			</script>";
    	}
    }

    public function delete(){
    	$id = (int)I('post.id');
    	$product = M('product');
    	$res = $product -> where('id = "'.$id.'"') -> delete();
    	if($res){
    		echo 1;
    	}else{
    		echo 2;
    	}
    }

    public function del(){
    	$product = M('product');

    	$id = I('post.id');
    	if(empty($id)){
    		echo "<script>
				alert('删除失败');
				window.location.href='".U('Admin/Product/index')."';
    		</script>";
    		die();
    	}
    	//转为字符串
    	$did = implode(',',$id);
    	//in 方法
    	$where['id'] = array('in',$did);

    	$res = $product -> where($where) -> delete();
    	if($res){
    		echo "<script>
				alert('删除成功');
				window.location.href='".U('Admin/Product/index')."';
    		</script>";
    	}else{
    		echo "<script>
				alert('删除失败');
				window.location.href='".U('Admin/Product/index')."';
    		</script>";
    	}
    }
}